package com.testword.controller;

import com.testword.entity.WordDifficulty;
import com.testword.entity.dto.QuestionDto;
import com.testword.entity.dto.UserDto;
import com.testword.entity.po.Record;
import com.testword.entity.po.Wordtable;
import com.testword.entity.query.RecordQuery;
import com.testword.entity.query.WordtableQuery;
import com.testword.entity.vo.ResponseVO;
import com.testword.mappers.RecordMapper;
import com.testword.mappers.WordtableMapper;
import com.testword.service.DifficultyService;
import com.testword.service.RecordService;
import com.testword.utils.MyThread;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;


@RestController

@CrossOrigin(origins = "*",maxAge = 3600)
public class RecordController extends ABaseController{

	private static final Logger logger = LoggerFactory.getLogger(RecordController.class);
	@Resource
	private RecordService recordService;

	@Resource
	private RecordMapper<Record,RecordQuery> recordMapper;

	@Resource
	private WordtableMapper<Wordtable, WordtableQuery> wordTableMapper;

	@Autowired
	private DifficultyService difficultyService;

	private List<WordDifficulty> allDifficulties; // 存储所有单词的难度值
	private static MyThread myThread;
	private static  List<Integer> candidates;

	@PostConstruct
	public void init() {
		this.allDifficulties = difficultyService.getAllDifficulties();
		myThread = new MyThread("时间记录线程"); // 初始化myThread
		candidates=selectAlltWord(allDifficulties);
//		List<String> words=difficultyService.getWords();
//		difficultyService.calculateDifficulty(words);
	}

	private  List<Double> difficulties = new ArrayList<>();
	private static QuestionDto questionDto = new QuestionDto();
	private static Record record = new Record();
	private static Wordtable wordtable = new Wordtable();
	private long millisDiff;
	private boolean know;
	private Integer nextWordIdx;
	@RequestMapping("/loadDataList")
	public ResponseVO loadDataList(RecordQuery query) {
		return getSuccessResponseVO(recordService.findListByPage(query));
	}

	/**
	 * 新增
	 */
	@RequestMapping("/add")
	public ResponseVO add(Record bean) {
		this.recordService.add(bean);
		return getSuccessResponseVO(null);
	}

	/**
	 * 批量新增
	 */
	@RequestMapping("/addBatch")
	public ResponseVO addBatch(@RequestBody List<Record> listBean) {
		this.recordService.addBatch(listBean);
		return getSuccessResponseVO(null);
	}

	/**
	 * 批量新增/修改
	 */
	@RequestMapping("/addOrUpdateBatch")
	public ResponseVO addOrUpdateBatch(@RequestBody List<Record> listBean) {
		this.recordService.addOrUpdateBatch(listBean);
		return getSuccessResponseVO(null);
	}

	/**
	 * 根据StudentId查询
	 */
	@RequestMapping("/getRecordByStudentId")
	public ResponseVO getRecordByStudentId(String studentId) {
		return getSuccessResponseVO(this.recordService.getRecordByStudentId(studentId));
	}

	/**
	 * 根据StudentId修改
	 */
	@RequestMapping("/updateRecordByStudentId")
	public ResponseVO updateRecordByStudentId(Record bean, String studentId) {
		this.recordService.updateRecordByStudentId(bean,studentId);
		return getSuccessResponseVO(null);
	}

	/**
	 * 根据StudentId删除
	 */
	@RequestMapping("/deleteRecordByStudentId")
	public ResponseVO deleteRecordByStudentId(String studentId) {
		this.recordService.deleteRecordByStudentId(studentId);
		return getSuccessResponseVO(null);
	}


	@RequestMapping("/record/rank")
	public ResponseVO rank(){
		RecordQuery recordQuery = new RecordQuery();
		recordQuery.setOrderBy("vocabulary desc,duration desc");
		List<UserDto> userDtoList = recordMapper.selectListByTwoTable(recordQuery);
		return getSuccessResponseVO(userDtoList);
	}


	@RequestMapping("/work/test")
	public ResponseVO question(String studentId,Boolean cognition) {
		 know=cognition;
		if(questionDto.getQuestionNum()==0 ){ //第一次过来等于null，后面就不会等于null了，直到重置为止
			questionDto = new QuestionDto();
			record = new Record();
			myThread.setDateTime(LocalDateTime.now());
		}
		//开始选词
		//在创建开始的时候，已经创建了candidates，这时候需要根据questionbnum的数量来直接从candidates取

		if(questionDto.getQuestionNum()!=50){nextWordIdx=candidates.get(questionDto.getQuestionNum());}
			//如果不是第一次进入，那么记录当前的Indicaes和是否正确
			if(!(questionDto.getQuestionNum()==0)){
				questionDto.getUsedIndices().add(nextWordIdx);
				questionDto.getKnows().add(know);
			}
			questionDto.setQuestionNum(questionDto.getQuestionNum()+1);
			//判断，如果是41，那么结束
			if(questionDto.getQuestionNum()==50){
				logger.info("now question num is:"+questionDto.getQuestionNum());
			}
			if(questionDto.getQuestionNum() == 51){
				//结束的时候，计算词汇量
				//计算当前的时间，得出总体的时间、
				LocalDateTime nowLocalDateTime= LocalDateTime.now();
				millisDiff =nowLocalDateTime.toInstant(ZoneOffset.UTC).toEpochMilli()-myThread.getDateTime()
						.toInstant(ZoneOffset.UTC)  // 转换为Instant（带时区）
						.toEpochMilli();
				// 转换为秒（保留小数）
				double secondsDiff = millisDiff / 1000.0;
				//此时得到总时间secondDiff，s为单位

				//根据questDTO中的know来计算
				//定义每个levle的词组的系数
				List<Integer> Coefficient= Arrays.asList(3000,6000,7000,10000,15000);
				List<Boolean> knowArray=questionDto.getKnows();
				List<Integer> arrayVolcabularyNum=new ArrayList<>();
				Integer wordCount=0;
				//遍历每一个答对的题，累加预估总词数。如果题目属于第一级, 则将第一级答对的比率乘以固定的预估值作为该题预估词数。
				// 如果题目不属于第一级, 则将上一级答对的比率和本级相乘，然后用这个比率乘以固定的预估值作为该题预估词数。
				// 如果上一级全部答错, 则将上一级的答对比率固定设置为0.1
				int levelKnowNum = 0;
				List<Double> rates = new ArrayList<>();
				for(int i=0;i<5;i++) {
					levelKnowNum = 0;
					for (int j = i * 10; j < 10 + i * 10; j++) {
						if (knowArray.get(j)) {
							levelKnowNum++;
						}
					}
					Double rate = 0.0;
					if (i == 0) {
						rate =(double) levelKnowNum / 10.0;
					} else {
						rate =(double) levelKnowNum / 10.0 * rates.get(i - 1);//显式转换为double类型
					}
					//如果上难度题目全错，那么系数设为0.1
					if (levelKnowNum == 0) {
						rate = 0.1;
					};
					rates.add(rate);
					Integer volcabularyNum = (int) (Coefficient.get(i) * rates.get(i));
					arrayVolcabularyNum.add(volcabularyNum);
					wordCount += volcabularyNum;
				}


				//开始计算总的单词量，综合答题时间+题目系数
				// 8分钟对应的秒数
				int EIGHT_MINUTES_IN_SECONDS = 2 * 60; // 480秒

				// 计算差值的绝对值（确保结果为正数）
				double absDiff = Math.abs(secondsDiff - EIGHT_MINUTES_IN_SECONDS);

				// 将结果转换为Integer类型（四舍五入或截断取决于需求）
				Integer secondResult = (int) Math.round(absDiff); // 四舍五入到最接近的整数

				Integer timeCount = (secondResult)*20;
				if(timeCount>1200){
					timeCount=1200;
				}
				wordCount=wordCount+timeCount;
				record.setVocabulary(wordCount);
				//创建VO对象并且赋值
				ResponseVO responseVO = getSuccessResponseVO(record.getVocabulary());
				responseVO.setStatus(ABaseController.STATUC_ERROR);

				record = new Record();
				questionDto = new QuestionDto();
				questionDto.setQuestionNum(0);
				difficulties = new ArrayList<>();
				return  responseVO;
			}else{
				String word = wordTableMapper.getWordBody(nextWordIdx);
				wordtable=new Wordtable();
				return getSuccessResponseVO(word);
			}

	}





	//选词策略
	private List<Integer> selectAlltWord(List<WordDifficulty> allDifficulties) {
		List<Integer> candidates = new ArrayList<>();
		while (candidates.size() < 50) {
			int i = candidates.size() / 10;
			if (i < 4) {
				//具体选取每一个levelword
				Integer nexIndex =selectRandomInRange(allDifficulties,i,i+1);
				if (!candidates.contains(nexIndex)) {
					candidates.add(nexIndex);
				}
			}else{
				Integer nexIndex =selectRandomInRange(allDifficulties,i,i+3);
				if (!candidates.contains(nexIndex)) {
					candidates.add(nexIndex);
				}
			}
		}
		return candidates;
	}
	private static final Random random = new Random();
		public  Integer selectRandomInRange (List < WordDifficulty> wordDifficulties,double min, double max) {
			if (wordDifficulties == null || wordDifficulties.isEmpty() || min > max) {
				return null;
			}

			// 使用二分查找定位第一个difficulties >= min的元素
			int left = 0;
			int right = wordDifficulties.size() - 1;
			int startIndex = -1;

			while (left <= right) {
				int mid = left + (right - left) / 2;
				double midDifficulty = wordDifficulties.get(mid).getDifficulties();

				if (midDifficulty >= min) {
					startIndex = mid;
					right = mid - 1;
				} else {
					left = mid + 1;
				}
			}

			// 如果没有找到符合条件的元素，返回null
			if (startIndex == -1) {
				return null;
			}

			// 定位最后一个difficulties <= max的元素
			left = startIndex;
			right = wordDifficulties.size() - 1;
			int endIndex = -1;

			while (left <= right) {
				int mid = left + (right - left) / 2;
				double midDifficulty = wordDifficulties.get(mid).getDifficulties();

				if (midDifficulty <= max) {
					endIndex = mid;
					left = mid + 1;
				} else {
					right = mid - 1;
				}
			}

			// 如果没有找到符合条件的元素，返回null
			if (endIndex == -1) {
				return null;
			}

			// 计算可选范围的大小
			int count = endIndex - startIndex + 1;
			if (count <= 0) {
				return null;
			}

			// 随机选择一个索引，并返回对应的WordDifficulty对象的id
			int randomIndex = startIndex + random.nextInt(count);
			return wordDifficulties.get(randomIndex).getId();
		}
}


